package com.hashcoding.eyes.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.hashcoding.eyes.R;
import com.hashcoding.eyes.data.entity.LoginInfoList;
import com.hashcoding.eyes.module.manager.LoginManager;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity implements Handler.Callback {

    private final int MSG_CHECK_LOGIN = 0x02;
    private final int MSG_START_MAIN = 0x03;

    private final int DELAY_TIME_MAX = 3000;
    private final int DELAY_TIME_MIN = 1000;

    @Bind(R.id.username)
    EditText mUsername;
    @Bind(R.id.password)
    EditText mPassword;

    private Handler mHandler;

    private String mUserID;
    private String mUserPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        mHandler = new Handler(this);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_CHECK_LOGIN:
                checkLogin();
                break;
            case MSG_START_MAIN:
                goNextView();
                return true;
        }
        return false;
    }

    private void checkLogin() {
        if (LoginInfoList.instance().login(mUserID, mUserPassword)) {
            LoginManager.instance().set(mUserID);
            mHandler.sendEmptyMessage(MSG_START_MAIN);
        } else {
            shortToast("用户名或密码错误");
        }
    }

    private void goNextView() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @OnClick(R.id.login)
    protected void onLogin() {
        mUserID = mUsername.getText().toString();
        mUserPassword = mPassword.getText().toString();

        mHandler.sendEmptyMessage(MSG_CHECK_LOGIN);
    }

    @OnClick(R.id.register)
    protected void onRegister() {
        startActivity(new Intent(this, RegisterActivity.class));
    }
}
